package ltd.bugs.cute.access.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ltd.bugs.cute.access.dao.IpAccessDAO;
import ltd.bugs.cute.access.model.IpAccess;
import ltd.bugs.cute.cache.CacheClient;
import ltd.bugs.cute.cache.CacheKeyUtil;
import ltd.bugs.cute.cache.callback.GetCallback;

@Service
public class IpAccessService {
  @Autowired
  private IpAccessDAO ipAccessDAO;
  private CacheKeyUtil keyUtil = new CacheKeyUtil(IpAccess.class);

  public void add(IpAccess ipAccess) {
    ipAccessDAO.add(ipAccess);
    CacheClient.remove(keyUtil.getGroupKey(".clientid." + ipAccess.getClientId()));
  }

  public void update(IpAccess ipAccess) {
    ipAccessDAO.update(ipAccess);
    // 删除该机构对应的所有IP缓存，为方便处理让该机构所有的IP白名单缓存失效，记录不多，所以性能上基本一样
    CacheClient.remove(keyUtil.getGroupKey(".clientid." + ipAccess.getClientId()));
  }

  public void delete(long id) {
    IpAccess ipAccess = ipAccessDAO.getById(id);
    ipAccessDAO.delete(id);
    // 删除该机构对应的所有IP缓存，为方便处理让该机构所有的IP白名单缓存失效，记录不多，所以性能上基本一样
    CacheClient.remove(keyUtil.getGroupKey(".clientid." + ipAccess.getClientId()));
  }

  public void deleteByClientId(long clientId) {
    ipAccessDAO.deleteByClientId(clientId);
    // 删除该机构对应的所有IP缓存，为方便处理让该机构所有的IP白名单缓存失效，记录不多，所以性能上基本一样
    CacheClient.remove(keyUtil.getGroupKey(".clientid." + clientId));
  }

  public IpAccess get(long clientId, String ip) {
    return CacheClient.get(keyUtil.getRecKey(".clientid." + clientId + ".ip." + ip),
        new GetCallback<IpAccess>() {

          @Override
          public String getCacheGroup() {
            // 结果放到组里面
            return keyUtil.getGroupKey(".clientid." + clientId);
          }

          @Override
          public IpAccess getObject() {
            return ipAccessDAO.get(clientId, ip);
          }
        });
  }

  public IpAccess getById(long id, long clientId) {
    return CacheClient.get(keyUtil.getRecKey("." + id), new GetCallback<IpAccess>() {

      @Override
      public String getCacheGroup() {
        return keyUtil.getGroupKey(".clientid." + clientId);
      }

      @Override
      public IpAccess getObject() {
        return ipAccessDAO.getById(id);
      }
    });
  }

  public List<IpAccess> getByClientId(long clientId) {
    return CacheClient.get(keyUtil.getRecKey(".clientId." + clientId),
        new GetCallback<List<IpAccess>>() {

          @Override
          public String getCacheGroup() {
            return keyUtil.getGroupKey(".clientid." + clientId);
          }

          @Override
          public List<IpAccess> getObject() {
            return ipAccessDAO.getByClientId(clientId);
          }
        });
  }
}
